import { useEffect } from 'react';
import request from 'umi-request';
import { message } from 'antd';
import { registerMicroApps } from 'qiankun';
import { useModel } from '@@/plugin-model/useModel';
import { start } from 'qiankun';

export default function MainLayout(props: any) {
  const { config, setConfig } = useModel('config');
  const { loginUser, setLoginUser } = useModel('loginUser');

  const loadLoginUser = (): void => {
    const loginUserValue = sessionStorage.getItem('LoginUser');
    if (loginUserValue) {
      setLoginUser(JSON.parse(loginUserValue));
    }
  };

  const loadConfig = () => {
    request
      .get('/mobile/config/config.json')
      .then((resp) => {
        document.title = resp.title;
        localStorage.setItem(
          'IconScriptUrl',
          JSON.stringify([resp.iconfontUrl]),
        );
        localStorage.setItem('LoginUrl', resp.loginUrl);
        setConfig(resp);
      })
      .catch((err) => {
        message.error('获取布局配置错误');
        throw err;
      });
  };

  const loadMicros = () => {
    request
      .get('/mobile/config/apps.json')
      .then((apps) => {
        apps.forEach((app: any) => {
          app.props = {
            config: config,
            loginUser: loginUser,
          };
        });
        registerMicroApps(apps);
        start({
          prefetch: false,
          singular: false,
        });
      })
      .catch((err) => {
        message.error('获取子应用配置错误');
        throw err;
      });
  };

  useEffect(() => {
    loadLoginUser();
    loadConfig();
  }, []);

  useEffect(() => {
    if (config) {
      if (loginUser) {
        loadMicros();
      } else {
        debugger;
        props.history.push(config?.loginUrl || 'login');
        return;
      }
    }
  }, [config, loginUser]);

  return <>{props.children}</>;
}
